/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.bean.database.event;

import com.jb.web.bean.Form;
import com.jb.web.bean.ListBean;
import com.jb.web.bean.event.UIEvent;
import com.jb.web.bean.event.UIEventHandler;
import com.jb.web.context.WebContext;

import java.sql.SQLException;


public class OnCreateTable implements UIEventHandler {
    public void handleEvent(WebContext pCtx, UIEvent event) {
        Form form = (Form) event.getSource();
        String tableName = event.getParameter("tableName");
        String createStmt = "create table " + tableName + " (";

        ListBean lb = (ListBean) form.getDescendantByClientId("fields");

        for (int i = 0; i < lb.getBlockSize(); i++) {
            String name = event.getParameter("cn" + (i));
            String type = event.getParameter("dt" + (i));
            String length = event.getParameter("len" + (i));

            if ((name == null) || (name.length() == 0)) {
                break;
            }

            if (type.equalsIgnoreCase("varchar")) {
                if ((length == null) || (length.length() == 0)) {
                    length = "16";
                }

                type = type + "(" + length + ")";
            }

            createStmt += (name + " " + type);

            if (i < (lb.getBlockSize() - 1)) {
                createStmt += ",";
            }
        }

        if (createStmt.endsWith(",")) {
            createStmt = createStmt.substring(0, createStmt.length() - 1);
        }

        createStmt += ");";

        try {
            com.jb.framework.database.UpdateDBCommand.executeStmt(createStmt);
            pCtx.addErrorMessage(form, "Table has been created!");
        } catch (SQLException e) {
            pCtx.addErrorMessage(form, "Failed to create table " + createStmt + " due to " + e);
        }
    }
}
